package com.linb.pan.lock.core.key;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.google.common.base.Joiner;
import com.linb.pan.lock.core.LockContext;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class StandardKeyGenerator extends AbstractKeyGenerator {

    /**
     * 标准key的生成方法
     * 格式：className : methodName : parameterType1 : ... : value1 : value2 : ...
     */
    @Override
    protected String doGenerateKey(LockContext lockContext, Map<String, String> keyValueMap) {
        List<String> keyList = Lists.newArrayList();
        //className
        keyList.add(lockContext.getClassName());
        //methodName
        keyList.add(lockContext.getMethodName());
        Class[] parameterTypes = lockContext.getParameterTypes();
        //parameterType1 parameterType2 ...
        if (ArrayUtil.isNotEmpty(parameterTypes)) {
            Arrays.stream(parameterTypes).forEach(parameterType -> {
                keyList.add(parameterType.toString());
            });
        } else {
            keyList.add(Void.class.toString());
        }
        //value1 value2 ...
        Collection<String> values = keyValueMap.values();
        if (CollectionUtil.isNotEmpty(values)) {
            values.stream().forEach(value -> keyList.add(value));
        }
        //分割开来
        log.info("以逗号分割后的keyList = {}", Joiner.on(",").join(keyList));
        return Joiner.on(",").join(keyList);
    }

}
